package com.example.demo.aop;

import com.example.demo.dto.StudentDTO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class DistributedLockAspect {

    private ExpressionParser parser = new SpelExpressionParser();
    private LocalVariableTableParameterNameDiscoverer nameDiscoverer = new LocalVariableTableParameterNameDiscoverer();


    @Pointcut(value = "@annotation(distributedLock)")
    public void distributedLockAnnotationPointcut(DistributedLock distributedLock) {
    }

    @Around(value = "distributedLockAnnotationPointcut(distributedLock)")
    public Object around(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable {
        try {
            System.out.println("环绕通知的目标方法名：" + joinPoint.getSignature().getName());
            System.out.println(distributedLock.value());
            System.out.println(distributedLock.key());
            System.out.println(generateKeyBySpEL(distributedLock.key(), joinPoint));

            System.out.println("around");

            LockManager.getInstance().setLock("let go lock");
//            if (true) {
//                return StudentDTO.builder().name("李四").build();
//            }
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            System.out.println("异常了");
            throw throwable;
        } finally {
            System.out.println("lock around");
        }
    }

    private String generateKeyBySpEL(String spELString, ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] paramNames = nameDiscoverer.getParameterNames(methodSignature.getMethod());
        Expression expression = parser.parseExpression(spELString);
        EvaluationContext context = new StandardEvaluationContext();
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            context.setVariable(paramNames[i], args[i]);
        }
        return expression.getValue(context).toString();
    }
}
